package com.itheima.interceptors;

import com.itheima.utils.JwtUtil;
import com.itheima.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptors implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        try {
            String token = request.getHeader("Authorization");
            // String tokenRedis = redisTemplate.opsForValue().get(token);
            Map<String, Object> clams = JwtUtil.parseToken(token);
            if(clams == null){
                throw new RuntimeException();
            }
            Integer id = (Integer) clams.get("id");
            String username = (String) clams.get("username");
            String tokenKey = id + username;
            String tokenRedis = redisTemplate.opsForValue().get(tokenKey);
            if(tokenRedis == null){
                throw new RuntimeException();
            }
            ThreadLocalUtil.set(clams);
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 释放线程中存储的变量
        ThreadLocalUtil.remove();
    }
}
